package com.sz.biz.common.sup.service.impl;

import com.google.common.collect.Lists;
import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.sup.entity.Supplier;
import com.sz.biz.common.sup.entity.SupplierBD;
import com.sz.biz.common.sup.entity.SupplierContact;
import com.sz.biz.common.sup.entity.SupplierTypeRel;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.common.sup.service.SupplierService;
import com.sz.biz.common.sup.dto.SupplierBdDto;
import com.sz.biz.common.sup.dto.SupplierDto;
import com.sz.biz.common.sup.dto.SupplierSearchDto;
import com.sz.biz.common.sup.dto.SupplierTypeRelDto;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.Pagination;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.service.SysFileGroupService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * Function: SupplierServiceImpl <br>
 * Author: wentao.chang <br>
 * Date: 2016-11-24 14:08:00
 */
@Service
public class SupplierServiceImpl extends AbstractService implements SupplierService {

    private static final String SUP_ = "sup_";
    @Autowired
    SysFileGroupService fileGroupService;
    @Autowired
    CustomerUserService customerUserService;

    /**
     * 保存供应商主信息
     *
     * @see SupplierService#saveSupplier(
     *SupplierDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public int saveSupplier(SupplierDto supplierDto) {
        checkMainDataValid(supplierDto);
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierDto, supplier);
        supplier.setIsAudited(supplierDto.isAudited());
        // 检查名字和编码
        //checkSupplierNameExist(supplier);
        checkSupplierCodeExist(supplier);
        //checkSupplierSimpleNameExist(supplier);

        supplier.setOrgId(0);
        supplier.setSignerId(0);
        supplier.setIsDeleted(false);

        dao.save("SupplierMapper.insert", supplier);

        // 保存供应商的types
        saveSupplierTypes(supplier.getId(), supplierDto);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.ADD, "新增供应商", dataBackup);
        return supplier.getId();
    }

    /**
     * @param supplierDto
     */
    @Transactional(propagation = Propagation.REQUIRED)
    void saveSupplierTypes(int supplierId, SupplierDto supplierDto) {
        dao.delete("SupplierTypeRelMapper.deleteBySupId", supplierId);
        List<String> supplierTypes = supplierDto.getServiceTypeCodes();
        if (supplierTypes != null && supplierTypes.size() > 0) {
            List<SupplierTypeRel> supplierTypeSave = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            for (String typeCode : supplierTypes) {
                if (StringUtils.isEmpty(typeCode) || map.get(typeCode) != null) {
                    continue;
                }
                map.put(typeCode + "", typeCode + "");
                SupplierTypeRel rel = new SupplierTypeRel();
                rel.setSupplierId(supplierId);
                rel.setServiceTypeCode(typeCode);
                supplierTypeSave.add(rel);
            }
            dao.batchInsert("SupplierTypeRelMapper.batchInsert", supplierTypeSave);
        }
    }


    private void checkMainDataValid(SupplierDto supplierDto) {
        if (CollectionUtils.isEmpty(supplierDto.getServiceTypeCodes())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "supplierTypeCodes");
        }
        //校验供应商类型
        if (supplierDto.getType() != CommCodes.SUPPLIER_TYPE_LOGISTICS && supplierDto.getType() != CommCodes.SUPPLIER_TYPE_TRADE) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "type");
        }
        supplierDto.setName(getCheckedTrimString(supplierDto.getName(), "name"));
        supplierDto.setSimpleName(getCheckedTrimString(supplierDto.getSimpleName(), "simpleName"));
        supplierDto.setCode(getCheckedTrimString(supplierDto.getCode(), "code"));
    }

    /**
     * 查询一个供应商
     *
     * @see SupplierService#findById(int)
     */
    @Override
    public SupplierDto findById(int supId) {
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supId);
        checkSupplierValid(supplier, supId);
        SupplierDto dto = new SupplierDto();
        BeanUtils.copyProperties(supplier, dto);
        dto.setAudited(supplier.getIsAudited());
        List<SupplierContact> rels = dao.findForList("SupplierContactMapper.findBySupId", supId, SupplierContact.class);
        dto.setSupplierContacts(rels);
        //供应商类型
        List<SupplierTypeRelDto> stypes =
                dao.findForList("SupplierTypeRelMapper.findBySupId", supId, SupplierTypeRelDto.class);
        dto.setServiceTypes(stypes);
        //联系人
        List<SupplierContact> cons = dao.findForList("SupplierContactMapper.findBySupId", supId, SupplierContact.class);
        dto.setSupplierContacts(cons);
        //BD
        List<SupplierBdDto> bds = dao.findForList("SupplierBDMapper.findBySupId", supId, SupplierBdDto.class);
        dto.setBds(bds);
        //附件
        if (!StringUtils.isEmpty(supplier.getPicture())) {
            List<FileInfoDto> attachs = fileGroupService.getFileDtosByGroupId(supplier.getPicture());
            dto.setFiles(attachs);
        }

        return dto;
    }

    /**
     * 查询一个供应商
     *
     * @see SupplierService#findById(int)
     */
    @Override
    public Supplier findSimpleById(int supId) {
        return (Supplier) dao.findForObject("SupplierMapper.findById", supId);
    }

    /**
     * 查询多个供应商
     *
     * @see SupplierService#findSimpleByIds(List)
     */
    @Override
    public List<Supplier> findSimpleByIds(List<Integer> supIds) {
        return dao.findForList("SupplierMapper.findByIds", supIds, Supplier.class);
    }

    private void checkBdDataValid(SupplierBD bd) {
        if (bd.getBdId() == null || bd.getBdId() == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "bdId");
        }
    }

    @Override
    public boolean validSupplierBd(int sid, int id, int bdid) {
        List<SupplierBdDto> bds = dao.findForList("SupplierBDMapper.findBySupId", sid, SupplierBdDto.class);
        boolean isValid = true;
        if (!CollectionUtils.isEmpty(bds)) {
            for (SupplierBdDto bd : bds) {
                if (bd.getBdId() == bdid && id != bd.getId()) {
                    isValid = false;
                }
            }
        }
        return isValid;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void updateSupplierBd(int supplierId, int entryid, SupplierBD bd) {
        SupplierBD supplierBDExist = (SupplierBD) dao.findForObject("SupplierBDMapper.findById", entryid);
        if (supplierBDExist.getSupplierId() != supplierId) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "bdid" + entryid + "~" + "supplierId" + supplierId);
        }
        supplierBDExist.setBdId(bd.getBdId());
        checkBdDataValid(supplierBDExist);

        SupplierDto dto = findById(supplierId);
        for (SupplierBdDto bddto : dto.getBds()) {
            //删除这条数据
            if (bddto.getBdId() == bd.getBdId() && bddto.getId() != entryid) {
                int[] bdids = new int[1];
                bdids[0] = bd.getBdId();
                deleteSupplierBds(supplierId, bdids);
            }
        }

        supplierBDExist.setResponsibility(bd.getResponsibility());
        supplierBDExist.setDescription(bd.getDescription());
        dao.update("SupplierBDMapper.update", supplierBDExist);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", bd);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商BD信息", dataBackup);
    }

    /**
     * @param sid
     * @param bd
     * @return
     */
    @Override
    public void saveSupplierBd(int sid, SupplierBD bd) {
        bd.setSupplierId(sid);
        checkBdDataValid(bd);
        SupplierDto dto = findById(sid);
        for (SupplierBdDto bddto : dto.getBds()) {
            //删除这条数据
            if (bddto.getBdId() == bd.getBdId()) {
                int[] bdids = new int[1];
                bdids[0] = bd.getBdId();
                deleteSupplierBds(sid, bdids);
            }
        }
        dao.save("SupplierBDMapper.insert", bd);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", bd);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商BD信息", dataBackup);
    }

    /**
     * @param sid
     * @param bdIds
     * @return
     */
    @Override
    public void deleteSupplierBds(int sid, int[] bdIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("sid", sid);
        map.put("list", bdIds);
        dao.delete("SupplierBDMapper.deleteBySupplierIdAndBdIds", map);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", bdIds);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商BD信息", dataBackup);
    }


    /**
     * 异步校验供应商编码
     *
     * @param sid
     * @param code
     * @return
     */
    @Override
    public void supplierCodeCheck(int sid, String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", sid);
        map.put("code", code);
        List<Supplier> listCode = dao.findForList("SupplierMapper.findByCode", map, Supplier.class);
        if (listCode.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_CODE_EXIST);
        }
    }

    /**
     * 异步校验供应商简称
     *
     * @param sid
     * @param simpleName
     * @return
     */
    @Override
    public void supplierSimpleNameCheck(int sid, String simpleName) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", sid);
        map.put("simpleName", simpleName);
        List<Supplier> listName = dao.findForList("SupplierMapper.findBySimpleName", map, Supplier.class);
        if (listName.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_FULLNAME_EXIST);
        }
    }

    /**
     * 异步校验供应商名称
     *
     * @param sid
     * @param name
     * @return
     */
    @Override
    public void supplierNameCheck(int sid, String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", sid);
        map.put("name", name);
        List<Supplier> listName = dao.findForList("SupplierMapper.findByName", map, Supplier.class);
        if (listName.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NAME_EXIST);
        }
    }


    private void checkSupplierNameExist(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", supplier.getId());
        map.put("name", supplier.getName());
        List<Supplier> listName = dao.findForList("SupplierMapper.findByName", map, Supplier.class);
        if (listName.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NAME_EXIST, supplier.getName());
        }
    }

    private void checkSupplierSimpleNameExist(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", supplier.getId());
        map.put("simpleName", supplier.getSimpleName());
        List<Supplier> listName = dao.findForList("SupplierMapper.findBySimpleName", map, Supplier.class);
        if (listName.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_FULLNAME_EXIST, supplier.getSimpleName());
        }
    }

    private void checkSupplierCodeExist(Supplier supplier) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", supplier.getId());
        map.put("code", supplier.getCode());
        List<Supplier> listCode = dao.findForList("SupplierMapper.findByCode", map, Supplier.class);
        if (listCode.size() > 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_CODE_EXIST, supplier.getCode());
        }
    }

    /**
     * 更新供应商主信息
     *
     * @see SupplierService#updateSupplierMain(int,
     * SupplierDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public int updateSupplierMain(int supplierId, SupplierDto supplierDto) {
        checkMainDataValid(supplierDto);
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        checkSupplierValid(supplier, supplierId);
        BeanUtils.copyProperties(supplierDto, supplier);
        supplier.setId(supplierId);
        //checkSupplierNameExist(supplier);
        checkSupplierCodeExist(supplier);
        dao.update("SupplierMapper.updateMain", supplier);
        // 保存供应商的types
        saveSupplierTypes(supplier.getId(), supplierDto);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商信息", dataBackup);
        return supplier.getId();
    }

    private void checkSupplierValid(Supplier supplier, int supId) {
        if (supplier == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND, supId);
        }
        if (supplier.getIsDeleted()) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_HAS_DELETED, supId);
        }
    }

    /**
     * 更新供应商业务信息
     *
     * @see SupplierService#updateSupplierMain(int,
     * SupplierDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public int updateSupplierBiz(int supplierId, SupplierDto supplierDto) {
        checkBizDataValid(supplierDto);
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        checkSupplierValid(supplier, supplierId);
        BeanUtils.copyProperties(supplierDto, supplier);
        supplier.setId(supplierId);

        dao.update("SupplierMapper.updateBiz", supplier);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商业务信息", dataBackup);
        return supplier.getId();
    }

    private void checkBizDataValid(SupplierDto supplierDto) {
        supplierDto.setMainService(getCheckedTrimString(supplierDto.getMainService(), "mainService"));
    }

    /**
     * 更新供应商财务法人信息
     *
     * @see SupplierService#updateSupplierLeal(int,
     * SupplierDto)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public int updateSupplierLeal(int supplierId, SupplierDto supplierDto) {
        checkLealDataValid(supplierDto);
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        checkSupplierValid(supplier, supplierId);

        List<String> attachments = supplierDto.getAttachFileIds();

        if (CollectionUtils.isEmpty(attachments) && !StringUtils.isEmpty(supplier.getPicture())) {
            fileGroupService.removeAllFileFromGroup(supplier.getPicture());
        }

        if (CollectionUtils.isEmpty(attachments) && StringUtils.isEmpty(supplier.getPicture())) {
            //do nothing
        }

        if (!CollectionUtils.isEmpty(attachments) && !StringUtils.isEmpty(supplier.getPicture())) {
            String fileGroupId = fileGroupService.saveFileToGroup(supplier.getPicture(), attachments,
                    "biz.supplier.model", "供应商" + supplierId + "营业执照", AppDomain.OPERATION);
            supplier.setPicture(fileGroupId);
        }

        if (!CollectionUtils.isEmpty(attachments) && StringUtils.isEmpty(supplier.getPicture())) {
            String fileGroupId = fileGroupService.createFileGroup(attachments,
                    "biz.supplier.model", "供应商" + supplierId + "营业执照", AppDomain.OPERATION);
            supplier.setPicture(fileGroupId);
        }

        BeanUtils.copyProperties(supplierDto, supplier);
        supplier.setId(supplierId);

        dao.update("SupplierMapper.updateLeal", supplier);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商财务信息", dataBackup);
        return supplier.getId();
    }

    private void checkLealDataValid(SupplierDto supplierDto) {
        supplierDto.setTaxpayerNumber(getCheckedTrimString(supplierDto.getTaxpayerNumber(), "taxpayerNumber"));
        supplierDto.setBankAccount(getCheckedTrimString(supplierDto.getBankAccount(), "bankAccount"));
        supplierDto.setBankName(getCheckedTrimString(supplierDto.getBankName(), "bankName"));
        supplierDto.setLealPerson(getCheckedTrimString(supplierDto.getLealPerson(), "lealPerson"));
        supplierDto.setCompanyTel(getCheckedTrimString(supplierDto.getCompanyTel(), "companyTel"));
        supplierDto.setAddress(getCheckedTrimString(supplierDto.getAddress(), "address"));

        if (supplierDto.getAttachFileIds() == null || supplierDto.getAttachFileIds().size() == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "attachFileIds");
        }
    }

    /**
     * @param supplierId      supplierId
     * @param supplierContact dto
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void saveSupplierContact(int supplierId, SupplierContact supplierContact) {
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        checkSupplierValid(supplier, supplierId);

        supplierContact.setSupplierId(supplierId);
        checkContactDataValid(supplierContact);

        dao.save("SupplierContactMapper.insert", supplierContact);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplierContact);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商联系人信息", dataBackup);
    }

    /**
     * @param sid
     * @param cids
     * @return
     */
    @Override
    public void deleteSupplierContacts(int sid, int[] cids) {
        if (cids.length == 0) {
            return;
        }
        dao.delete("SupplierContactMapper.deleteByIds", cids);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", cids);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商联系人信息", dataBackup);
    }

    /**
     * @param supplierId      supplierId
     * @param supplierContact dto
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void updateSupplierContact(int supplierId, int contactId, SupplierContact supplierContact) {
        checkContactDataValid(supplierContact);
        SupplierContact supplierContactExist =
                (SupplierContact) dao.findForObject("SupplierContactMapper.findById", contactId);
        if (supplierContactExist.getSupplierId() != supplierId) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND,
                    "contactId" + contactId + "~" + "supplierId" + supplierId);
        }
        supplierContactExist.setTelephone(supplierContact.getTelephone());
        supplierContactExist.setResponsibility(supplierContact.getResponsibility());
        supplierContactExist.setPosition(supplierContact.getPosition());
        supplierContactExist.setDepartment(supplierContact.getDepartment());
        supplierContactExist.setMobilephone(supplierContact.getMobilephone());
        supplierContactExist.setName(supplierContact.getName());
        supplierContactExist.setDescription(supplierContact.getDescription());
        dao.update("SupplierContactMapper.update", supplierContactExist);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplierContact);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商联系人信息", dataBackup);
    }

    private void checkContactDataValid(SupplierContact contact) {
        contact.setName(getCheckedTrimString(contact.getName(), "name"));
        contact.setResponsibility(getCheckedTrimString(contact.getResponsibility(), "responsibility"));
        contact.setDepartment(getCheckedTrimString(contact.getDepartment(), "department"));
        contact.setPosition(getCheckedTrimString(contact.getPosition(), "position"));
    }


    /**
     * 删除某个供应商
     *
     * @see SupplierService#deleteSupplier(int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void deleteSupplier(int supplierId) {
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        checkSupplierValid(supplier, supplierId);
        supplier.setLastUpdateUserId(PrincipalUtils.getAccountId());
        dao.update("SupplierMapper.deleteById", supplierId);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "修改供应商主信息", dataBackup);
    }

    /**
     * 审核供应商
     *
     * @see SupplierService#auditSupplier(int)
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void auditSupplier(int supplierId) {
        Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findById", supplierId);
        if (supplier == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_NOT_FOUND, supplierId);
        }
        if (supplier.getIsDeleted()) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_HAS_DELETED, supplierId);
        }
        if (supplier.getIsAudited()) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_HAS_AUDITED, supplierId);
        }
        supplier.setLastUpdateUserId(PrincipalUtils.getAccountId());
        dao.update("SupplierMapper.auditById", supplier);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UPDATE_SUPPLIER", supplier);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.UPDATE, "审核供应商信息", dataBackup);
    }

    /**
     * 批量删除供应商
     *
     * @see SupplierService#deleteSuppliers(int[])
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Error.class)
    public void deleteSuppliers(int[] supplierIds) {
        if (supplierIds.length == 0) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("lastUpdateUserId", PrincipalUtils.getAccountId());
        param.put("array", supplierIds);
        dao.update("SupplierMapper.deleteByIds", param);
        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_SUPPLIER", supplierIds);
        PrincipalLogUtils.addOperationLog(ModuleNames.BIZ, ModuleNames.BIZ_SUPPLIER, UserActions.DELETE, "删除供应商主信息", dataBackup);
    }

    /**
     * 查找供应商列表
     *
     * @see SupplierService#findSuppliersByFilterListPage(int, String,
     * java.lang.String, float, boolean, int, int)
     */
    @Override
    public ResultDto findSuppliersByFilterListPage(int type, String serviceTypeCode, String queryString, float rank,
                                                   boolean greaterthan, int pageIndex, int pageSize) {
        ParamData pd = new ParamData();
        pd.put("q", StringUtils.replaceSqlPattern(queryString));
        pd.put("serviceTypeCode", serviceTypeCode);
        pd.put("rank", rank);
        pd.put("greaterthan", greaterthan);
        pd.put("type", type);
        Pagination page = new Pagination();
        page.setCurrentPage(pageIndex);
        page.setPageSize(pageSize);
        pd.setPagination(page);

        List<Supplier> suppliers = dao.findForList("SupplierMapper.findByFilterListPage", pd, Supplier.class);

        List<SupplierDto> sDtos = new ArrayList<>();

        for (Supplier supplier : suppliers) {
            SupplierDto dto = new SupplierDto();
            BeanUtils.copyProperties(supplier, dto);
            dto.setAudited(supplier.getIsAudited());
            //BD
            List<SupplierBdDto> bds = dao.findForList("SupplierBDMapper.findBySupId",
                    supplier.getId(), SupplierBdDto.class);
            dto.setBds(bds);
            if (!CollectionUtils.isEmpty(bds)) {
                dto.setLinkMan(bds.get(0).getName());
                dto.setLinkTel(bds.get(0).getMobilephone());
            }
            sDtos.add(dto);
        }

        QResultDto dto = new QResultDto();
        dto.setData(sDtos);
        dto.setPagination(page);
        return dto;
    }


    /**
     * @param q q
     * @return ResultDto
     */
    @Override
    public ResultDto findSuppliersByFilter(String q, int pageIndex, int pageSize, int type) {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams qp = new QueryParams(pageSize, pageIndex, q, null);
        qp.put("type", type);
        ParamData pd = this.convertQueryParams(qp);
        List<Supplier> suppliers = dao.findForList("SupplierMapper.findByFilterSimpleListPage", pd, Supplier.class);

        return new QResultDto(suppliers, pd.getPagination());
    }

    @Override
    public SupplierDto findCurrTrdSupplier() {
        SupplierDto dto = null;
        String accountName = PrincipalUtils.getPrincipal().getAssociatedAccountName();
        if (!StringUtils.isEmpty(accountName) && accountName.startsWith(SUP_)) {
            String code = accountName.substring(4);
            Supplier supplier = (Supplier) dao.findForObject("SupplierMapper.findAllByCode", code);
            if (!ObjectUtils.isEmpty(supplier)) {
                dto = this.findById(supplier.getId());
            }
        }
        return dto;
    }

    @Override
    protected String getMapperNamespace() {
        return "-";
    }


    @Override
    public ResultDto findByFilterForOrder(QueryParams params, int type) {
        params.put("type", type);
        ParamData pd = this.convertQueryParams(params);
        //获取产品基本信息
        List<Supplier> suppliers = dao.findForList("SupplierMapper.findByFilterForOrderListPage", pd, Supplier.class);
        List<SupplierSearchDto> dtos = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(suppliers)) {
            for (Supplier supplier : suppliers) {
                SupplierSearchDto dto = new SupplierSearchDto();
                dto.setId(supplier.getId());
                dto.setCode(supplier.getCode());
                dto.setName(supplier.getName());
                dtos.add(dto);
            }
        }
        return new QResultDto(dtos, pd.getPagination());
    }

    @Override
    public List<Supplier> finByCreateTimeForRpt(Date dateBegin, Date dateEnd) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("dateBegin", dateBegin);
        map.put("dateEnd", dateEnd);
        return dao.findForList("SupplierMapper.finByCreateTimeForRpt", map, Supplier.class);
    }
}
